package com.zkingsoft.actions.admin;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zkingsoft.actions.common.BaseController;
import com.zkingsoft.anotations.RemoveRequestToken;
import com.zkingsoft.anotations.SaveRequestToken;
import com.zkingsoft.exception.GlobleException;
import com.zkingsoft.model.Course;
import com.zkingsoft.model.Paymentinfo;
import com.zkingsoft.model.Studentinfo;
import com.zkingsoft.model.Tuitioninfo;
import com.zkingsoft.plugin.pojo.PaginationVO;
import com.zkingsoft.plugin.util.DateUtils;
import com.zkingsoft.plugin.util.ExcelUtil;
import com.zkingsoft.plugin.util.WebUtil;
import com.zkingsoft.plugin.util.ExcelUtil.ViewExcel;
import com.zkingsoft.pojo.AjaxResult;
import com.zkingsoft.serviceUtil.ServiceUtil;
import com.zkingsoft.services.PaymentinfoService;
import com.zkingsoft.services.StudentinfoService;
import com.zkingsoft.services.TuitioninfoService;

/**
 * This field was generated by Zking.software.Codegen.
 * 
 * @date 2016-11-17 11:32
 */
@Controller
@RequestMapping(value = "admin/paymentinfo")
public class PaymentinfoController extends BaseController {

	@Resource
	private PaymentinfoService paymentinfoService;
	@Resource
	private StudentinfoService studentInfoService;
	@Resource
	private ServiceUtil serviceUtil;
	@Resource
	private TuitioninfoService currentService;

	/**
	 * 列表显示
	 */
	@RequestMapping(value = "/showList")
	public @ResponseBody AjaxResult showList(Paymentinfo paymentinfo, PaginationVO pageVo) {
		if (pageVo == null) {
			pageVo = new PaginationVO();
		}
		List<Paymentinfo> dataList = paymentinfoService.findInPage(paymentinfo, pageVo);
		AjaxResult result = new AjaxResult(AjaxResult.STATUS_OK, null, null, dataList,
				paymentinfoService.findTotal(paymentinfo));
		return result;
	}

	/**
	 * 新增或者修改页面
	 */
	// @RemoveRequestToken
	@RequestMapping(value = "/addOrModify")
	public @ResponseBody AjaxResult addOrModify(Paymentinfo paymentinfo) {
		Paymentinfo pan = new Paymentinfo();
		pan = paymentinfoService.findBysId(paymentinfo.getsId());
		Studentinfo studentInfo = studentInfoService.findById(paymentinfo.getsId());
		
		if (paymentinfo.getpId() != null) {
			/*Paymentinfo agoMoney = paymentinfoService.findById(paymentinfo.getpId());
			//判断已经交学费总额是否大于应交学费
			if((pan.gettInTuition()-agoMoney.getpMoney())+paymentinfo.getpMoney()>studentInfo.gettTuition()){
				throw new GlobleException("交费总额不能超过应交学费");
			}*/
			return modify(paymentinfoService, paymentinfo, "缴费");
		} 
		
		else {
			//判断缴费单号是否重复
			if (serviceUtil.addCheckRepeat("paymentinfo", "p_note", paymentinfo.getpNote())){
				 throw new GlobleException("此单号已经存在");
			}
			
			/*//判断已经交学费总额是否大于应交学费
			if(paymentinfo.getpMoney()>studentInfo.gettTuition() 
					|| (pan!=null && pan.gettInTuition()+paymentinfo.getpMoney()>studentInfo.gettTuition())){
				throw new GlobleException("交费总额不能超过应交学费");
			}*/
			return add(paymentinfoService, paymentinfo, "缴费");
		}
	}

	/**
	 * 进入修改界面
	 */
	// @SaveRequestToken
	@RequestMapping(value = "/editForm")
	public String editForm(Long id) {
		Paymentinfo paymentinfo;
		if (id != null) {
			paymentinfo = paymentinfoService.findById(id);
			WebUtil.getRequest().setAttribute("obj", paymentinfo);
		}
		return "admin/paymentinfo-form";
	}

	/**
	 * 删除
	 */
	@RequestMapping(value = "/del")
	public @ResponseBody AjaxResult del(String keys) {
		return remove(paymentinfoService, keys);
	}

	@RequestMapping(value = "/queryStuByClass")
	public @ResponseBody AjaxResult queryStuByClass(Studentinfo studentinfo) {
		List<Studentinfo> stuList = studentInfoService.findByModel(studentinfo);
		if (stuList != null && stuList.size() > 0) {
			return new AjaxResult(AjaxResult.STATUS_OK, null, "成功", stuList, stuList.size());
		}
		return new AjaxResult(AjaxResult.STATUS_ERR, null, "该班级没有学生");
	}
	
	/**
	 * 查询对象嗯真烦
	 * */
	@RequestMapping(value = "/findModel")
	public @ResponseBody AjaxResult findModel(Paymentinfo paymentinfo){
		AjaxResult result = new AjaxResult(AjaxResult.STATUS_OK,null,null,paymentinfoService.findByModel(paymentinfo),null);
		return result;
	}

	/**
	 * 
	 * @Description:导出excel
	 * @author:dingchuan
	 * @return 返回类型 ModelAndView
	 * @date 2017年2月15日
	 */
	/*@RequestMapping(value = "/exportExcel")
	public @ResponseBody ModelAndView report(ModelMap model, HttpServletRequest request, HttpServletResponse response,
			Paymentinfo paymentinfo) {
		try {
			if (paymentinfo.getsName() != null && !(paymentinfo.getsName().equals(""))) {
				paymentinfo.setsName(java.net.URLDecoder.decode(paymentinfo.getsName(), "UTF-8"));
			}
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		// 查询符合条件的数据
		List<Paymentinfo> dataList = paymentinfoService.findByModel(paymentinfo);
		SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DATE_FORMAT_DD);
		// 把数据组装成我们要的数据，外面的list表示一行数据，也就是一个对象的信息，对应到excel的一行数据。里面的list表示对象的一个属性，对应excel的单元格
		List<List<Object>> list = new ArrayList<>();
		for (Paymentinfo obj : dataList) {
			List<Object> temp = new ArrayList<>();
			temp.add(obj.getsNo());
			temp.add(obj.getsName());
			temp.add(obj.gettCourse());
			temp.add(obj.gettClass());
			temp.add(obj.gettTuition());
			temp.add(obj.gettInTuition());
			temp.add(obj.gettUnTuition());
			List<Paymentinfo> paymentList = obj.getPaymentList();
			for (Paymentinfo obj2 : paymentList) {
				temp.add(obj2.getpNote());
				temp.add(obj2.getpMoney());
				String dateStr = sdf.format(obj2.getpDate());
				temp.add(dateStr);
			}
			list.add(temp);
		}
		// 查找最大缴费次数
		int maxPayNum = paymentinfoService.findPayNumMax();
		// 创建一个excel对象
		HSSFWorkbook workbook = new HSSFWorkbook();
		//样式设置  
        HSSFCellStyle style = workbook.createCellStyle();

		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); 
		// 生成一个字体
		HSSFFont font = workbook.createFont();
		font.setColor(HSSFColor.VIOLET.index);
		font.setFontHeightInPoints((short) 12);
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		// 把字体应用到当前的样式
		style.setFont(font);

		HSSFCellStyle style2 = workbook.createCellStyle();
		// 设置上下左右边框
		style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		// 设置单元格背景色
		style.setFillForegroundColor(IndexedColors.WHITE.getIndex());
		style.setFillPattern(CellStyle.SOLID_FOREGROUND);

		// 建立新的sheet对象（excel的表单）
		HSSFSheet sheet = workbook.createSheet("缴费表");
		//设置缺省列高
		sheet.setDefaultRowHeightInPoints(30);
		
		// 在sheet里创建第一行，参数为行索引(excel的行)，可以是0～65535之间的任何一个
		HSSFRow row1 = sheet.createRow(0);
		// 创建单元格（excel的单元格，参数为列索引，可以是0～255之间的任何一个
		HSSFCell cell = row1.createCell(0);
		cell.setCellStyle(style);
		// 设置单元格内容
		cell.setCellValue("缴费信息列表");
		int maxRowNum = 6 + maxPayNum * 3;
		// 合并单元格CellRangeAddress构造参数依次表示起始行，截至行，起始列， 截至列
		sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, maxRowNum - 1));
		// 创建第二行
		HSSFRow row2 = sheet.createRow(1);
		row2.createCell(0).setCellValue("学号");
		row2.createCell(1).setCellValue("姓名");
		row2.createCell(2).setCellValue("课程");
		row2.createCell(3).setCellValue("所在班级");
		row2.createCell(4).setCellValue("应交学费");
		row2.createCell(5).setCellValue("已交学费");
		row2.createCell(6).setCellValue("未交学费");
		int nextCellNum = 7;
		for (int i = 1; i <= maxPayNum; i++) {
			row2.createCell(nextCellNum).setCellValue("缴费(" + i + ")");
			
			nextCellNum += 3;
		}
		// 合并第二、三行前6个单元格
		sheet.addMergedRegion(new CellRangeAddress(1, 2, 0, 0));
		sheet.addMergedRegion(new CellRangeAddress(1, 2, 1, 1));
		sheet.addMergedRegion(new CellRangeAddress(1, 2, 2, 2));
		sheet.addMergedRegion(new CellRangeAddress(1, 2, 3, 3));
		sheet.addMergedRegion(new CellRangeAddress(1, 2, 4, 4));
		sheet.addMergedRegion(new CellRangeAddress(1, 2, 5, 5));
		// 合并第二行的第6列，三个为一组
		int startCellNum = 6;
		for (int i = 1; i <= maxPayNum; i++) {
			sheet.addMergedRegion(new CellRangeAddress(1, 1, startCellNum, startCellNum + 2));
			startCellNum += 3;
		}
		// 创建第三行
		HSSFRow row3 = sheet.createRow(2);
		int nextCellNum2 = 6;
		
		// 开始填充数据
		for (int i = 0; i < list.size(); i++) {
			HSSFRow row4 = sheet.createRow(i + 3);// 第几行
			List<?> rowList = list.get(i);
			for (int j = 0; j < rowList.size(); j++) {
				String textValue = "";
				sheet.autoSizeColumn((short) j, true);
				Object value = rowList.get(j);
				HSSFCell cell2 = row4.createCell(j);// 第几列：从0开始
				if (value instanceof Integer) {
					cell2.setCellValue((Integer) value);
				} else if (value instanceof Float) {
					textValue = String.valueOf((Float) value);
					cell2.setCellValue(textValue);
				} else if (value instanceof Double) {
					textValue = String.valueOf((Double) value);
					cell2.setCellValue(textValue);
				} else if (value instanceof Long) {
					cell2.setCellValue((Long) value);
				} else if (value instanceof Boolean) {
					textValue = "是";
					if (!(Boolean) value) {
						textValue = "否";
					}
					cell2.setCellValue(textValue);
				} else {
					// 其它数据类型都当作字符串简单处理
					if (value != null) {
						textValue = value.toString();
					}
					cell2.setCellValue(textValue);
				}
				sheet.setColumnWidth(cell2.getColumnIndex(), 256 * 10);
			}
		}
		try {
			ViewExcel.buildExcel(null, workbook, request, response, "缴费信息.xls");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ModelAndView(new ViewExcel(), model);
	}*/

}